use axum::{
    extract::State,
    http::StatusCode,
    response::{Json},
};
use std::sync::Arc;
use tokio::sync::Mutex;

use crate::services::pbf_download::{PbfDownloadService, DownloadProgress};
use crate::utils::AppState;

// 全局下载状态
#[derive(Debug, Clone, Default)]
pub struct DownloadState {
    pub progress: Arc<Mutex<DownloadProgress>>,
    pub is_running: Arc<Mutex<bool>>,
}

// 下载PBF文件
pub async fn download_pbf(
    State(app_state): State<Arc<AppState>>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let mut is_running = app_state.download_state.is_running.lock().await;
    if *is_running {
        return Err((StatusCode::CONFLICT, "下载任务已在进行中".to_string()));
    }
    *is_running = true;
    drop(is_running);

    // 重置进度
    let mut progress = app_state.download_state.progress.lock().await;
    *progress = DownloadProgress::default();
    drop(progress);

    // 启动下载任务
    let download_service = PbfDownloadService::new(
        app_state.config.pbf_source_url.clone(),
        app_state.config.pbf_download_path(),
        app_state.config.max_download_speed,
        app_state.download_state.progress.clone(),
    );

    let app_state_clone = app_state.clone();
    tokio::spawn(async move {
        let result = download_service.download().await;
        if let Err(e) = result {
            tracing::error!("PBF下载失败: {}", e);
        }

        // 更新运行状态
        let mut is_running = app_state_clone.download_state.is_running.lock().await;
        *is_running = false;
    });

    Ok(Json(serde_json::json!({
        "status": "success",
        "message": "下载任务已启动",
        "path": app_state.config.pbf_download_path()
    })))
}

// 获取下载进度
pub async fn get_download_progress(
    State(app_state): State<Arc<AppState>>,
) -> Result<Json<DownloadProgress>, (StatusCode, String)> {
    let progress = app_state.download_state.progress.lock().await;
    Ok(Json(progress.clone()))
}
